
//  axios
import axios from "axios"
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);
//  vuex 状态
import store from './store'
// js-cookie
import Cookie from 'js-cookie'
// 引入公共方法
import common from './common/common';

// 请求是否登录
function is_login() {
  var data = {
    username: Cookie.get('username')
  }
  return axios.post('/admin/Index/is_login', data);
}

function intercept(to, from, next) {
  var no_login = to.meta.no_login,
    login = '/login',
    state = store.state;
  // 赋予路由信息
  state.route = to;
  // 修改页面标题和头部标题
  document.title = to.meta.title;
  state.header.title = to.meta.title;
  // 当去登录界面时
  if (to.path == '/login') {
    next();
    return false;
  }
  // 当不需要登录时
  if (no_login) {
    next();
    return false;
  }
  // 当没有登录时
  if (!Cookie.get("username")) {
    Cookie.remove("BJYSESSION");
    next(login)
    return false;
  }
  // 当有用户资料时
  if (state.user) {
    next();
    return false;
  }
  // 当刷新 判断是否登录
  is_login().then(ref => {
    var ref = ref.data;
    if (ref.state) {
      state.user = ref.data;
      next();
    } else {
      common.message({
        type: 'error',
        message:ref.info
      });
      Cookie.remove("username");
      Cookie.remove("BJYSESSION");
      next(login)
    }
  })
}

export default intercept